<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :areas="treeAreas" :area-type="areaType"  v-on:handleNodeClick="onHandleNodeClick" />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-select style="margin-left: 10px;width: 110px" class="filter-item" clearable v-model="listQuery.unit" placeholder="单元号">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input style="margin-left: 10px;width: 120px" class="filter-item" type="number" clearable v-model="listQuery.floor" placeholder="楼层"></el-input>
            <el-input style="margin-left: 10px;width: 120px" class="filter-item" type="number" clearable v-model="listQuery.room_number" placeholder="门牌号"></el-input>
            <el-select style="margin-left: 10px;width: 110px" class="filter-item" clearable v-model="listQuery.customer_type" placeholder="用户类型">
              <el-option
                v-for="item in customerTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button v-if="checkPermission('查询用户')"  style="margin-left:40px" class="filter-item" type="primary" icon="el-icon-search" @click="getCustomerList">
              查询
            </el-button>
            <el-button v-if="checkPermission('添加用户')" style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-plus" @click="createCustomer">
              新建
            </el-button>
            <el-button v-if="checkPermission('导入用户')" style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-upload" @click="importCustomers">
              导入
            </el-button>
            <el-button v-if="checkPermission('导出用户')" :loading="exportStatus"  style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-download" @click="exportCustomers">
              导出
            </el-button>
            <el-button v-if="checkPermission('删除用户')"   style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-delete" @click="handleDelete">
              删除
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :row-style="{height:0+'px'}"
              :cell-style="{padding:0+'px'}"
              :data="list"
              ref="customerTable"
              border
              fit
              stripe
              highlight-current-row
              height="700"
              style="width: 100%;"
            >
              <el-table-column
                type="selection"
                width="40">
              </el-table-column>
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column label="用户姓名" align="center" width="80">
                <template v-slot="{row}">
                  <span>{{row.customer_name}}</span>
                </template>
              </el-table-column>
              <el-table-column label="用户类型" align="center" width="80">
                <template v-slot="{row}">
                  <span>{{formatType(row.customer_type)}}</span>
                </template>
              </el-table-column>
              <el-table-column label="用户编号" align="center" width="160">
                <template v-slot="{row}">
                  <span>{{row.code}}</span>
                </template>
              </el-table-column>
              <el-table-column label="水司编号" align="center"  width="160">
                <template v-slot="{row}">
                  <span>{{row.refer_number || '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="手机" align="center" width="120">
                <template v-slot="{row}">
                  <span>{{row.mobile || '-'}}</span>
                </template>
              </el-table-column>
              <el-table-column label="地址" align="left" >
                <template v-slot="{row}">
                  <span>{{row.unit}}/{{row.floor}}层/{{row.room_number}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template v-slot="{row,$index}">
                  <el-button v-if="checkPermission('修改用户')" type="primary" icon="el-icon-edit" circle  @click="updateCustomer(row)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0"  :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getCustomerList" />

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" custom-class="window-small-width">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
                <el-form-item label="所属区域" prop="area" >
                  <area-selector :value="temp.area_path" :areas="treeAreas" :disable="dialogStatus != 'create'"  ref="areaSelector"  :area-type="areaType"  v-on:selectArea="onSelectArea"></area-selector>
                </el-form-item>
                <el-form-item label="用户类型" prop="customer_type" >
                  <el-select v-model="temp.customer_type" placeholder="请选择">
                    <el-option
                      v-for="item in customerTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="customer_name" >
                  <el-input v-model="temp.customer_name" />
                </el-form-item>
                <el-form-item label="手机" prop="mobile" >
                  <el-input v-model="temp.mobile" />
                </el-form-item>
                <el-form-item label="单元号" prop="unit" >
                  <el-select v-model="temp.unit" placeholder="请选择">
                    <el-option
                      v-for="item in units"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="楼层" prop="floor" >
                  <el-input v-model="temp.floor" />
                </el-form-item>
                <el-form-item label="门牌号" prop="room_number" >
                  <el-input v-model="temp.room_number" />
                </el-form-item>
                <el-form-item label="水司编号" prop="refer_number" >
                  <el-input v-model="temp.refer_number" />
                </el-form-item>
                <el-form-item label="证件类型" prop="identity_type" >
                  <el-select v-model="temp.identity_type" placeholder="请选择">
                    <el-option
                      v-for="item in idTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="证件编号" prop="identity_card" >
                  <el-input v-model="temp.identity_card" />
                </el-form-item>
                <el-form-item v-if="false" label="开户时间" prop="establish_time">
                  <el-date-picker
                    v-model="temp.establish_time"
                    type="date"
                    placeholder="开户时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="备注" prop="remark" label-width="80px">
                  <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="submitLoading" type="primary" @click="dialogStatus == 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog title="用户导入" :visible.sync="dialogImportVisible" custom-class="window-small-width">
                <el-form ref="importForm" :rules="rules" :model="temp" v-loading="formLoading" element-loading-text="正在导入数据，请稍后"
                         element-loading-spinner="el-icon-loading" label-position="right" label-width="60px">
                  <el-form-item label="" prop="building" >
                    <area-selector :areas="treeAreas"  ref="building" :area-type="areaType" v-on:selectArea="onSelectBuilding"></area-selector>
                  </el-form-item>
                  <el-form-item label="" prop="file" >
                    <el-upload
                      class="upload-demo"
                      drag
                      :data="importData"
                      :headers="{'x-Token':token}"
                      action="/meter/customer/import"
                      :on-success="handleImportSuccess"
                      :before-upload="beforeImport"
                    >
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                      <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过2M</div>
                      <div class="el-upload__tip" slot="tip">
                        尽量使用微软EXCEL,
                        <el-link type="primary" href="/resource/导入模板.xlsx">下载模板</el-link>
                      </div>

                    </el-upload>
                  </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="导入结果" :visible.sync="importResult.length > 0" width="35%" >
                <el-alert
                  :title="msg"
                  type="error"
                  v-for="msg in importResult"
                  :key="msg"
                  show-icon>
                </el-alert>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import AreaSelector from '@/components/area/AreaSelector'
import Pagination from '@/components/Pagination'
import {getCustomerList, addCustomer, deleteCustomer, updateCustomer,exportCustomers} from "@/api/customer";
import { getToken } from '@/utils/auth'
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission"
import {getCustomerTypeText} from "@/utils";


export default {
  name: 'customer-list',
  components:{AreaSelector, areas,Pagination},
  data() {
    const validateArea = (rule, value, callback) => {
      if (this.temp.area_code === '') {
        callback(new Error('请选择区域'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible:false,
      exportStatus:false,
      dialogImportVisible:false,
      dialogStatus:'create',
      tableKey:0,
      listLoading:true,
      submitLoading:false,
      importResult:[],
      formLoading:false,
      list:[],
      exportData :[],
      importData:'',
      areaType:2,
      idTypes:[{label:"请选择",value:0},{label:"身份证",value:1}, {label:"护照",value:2}, {label:"驾驶证",value:3}],
      units:['一单元','二单元','三单元','四单元','五单元','六单元','七单元','八单元','九单元','十单元'],
      temp:{
        id:0,
        area_code:'',
        area_path:'',
        area_name:'',
        customer_name:'',
        unit:'一单元',
        floor:1,
        customer_type:1,
        room_number:'',
        identity_card:'',
        identity_type:1,
        mobile:'',
        establish_time:'',
        refer_number:'',
      },
      total:0,
      textMap: {
        update: '编辑用户',
        create: '新建用户'
      },
      treeAreas:[],
      token:'',
      listQuery:{
        area_code:'',
        unit:'',
        floor:'',
        customer_type:0,
        page:1,
        pageSize:20,
        room_number:''
      },
      rules: {
        room_number: [{ required: true, message: '名称必填', trigger: 'blur' }],
        floor: [{ required: true, pattern:/^[0-9]*[1-9][0-9]*$/,message: '楼层输入错误', trigger: 'blur' }],
        unit: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
        area: [{ validator: validateArea, required: true,trigger: 'change' }]
      },
      fileTypes:['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
    };
  },
  created() {
    this.getCustomerList()
    this.getAreaTree()
    this.token = getToken()
  },
  computed: {
    customerTypes() {
      return this.$store.getters.customerType
    }
  },
  methods: {
    checkPermission,
    getAreaTree(){
      getAreaTree({type:2}).then(response => {
        this.treeAreas = response.data
      })
    },
    handleImportSuccess(res, file){
      this.formLoading =false
      this.importResult = res.message
      this.dialogImportVisible = false
      if(res.message.length === 0){
        this.$message.success('导入完成')
      }else{
        this.$message.error(res.message.join('<br>'))
      }
    },
    beforeImport(file){
      if (this.fileTypes.indexOf(file.type) === -1){
        this.$message.error('只允许导入微软excel文件');
        return false
      }
      if(file.size / 1024 / 1024 > 2 ){
        this.$message.error('文件大小限定2M');
        return false
      }
      if(this.importData === ''){
        this.$message.error('请选择一个区域');
        return false
      }
      this.formLoading = true
      return true
    },
    onHandleNodeClick:function (data) {
      if(this.listQuery.area_code !== data.code){
        this.listQuery.area_code = data.code
        this.getCustomerList()
      }
    },
    getCustomerList(){
      this.listLoading = true
      getCustomerList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    createCustomer(){
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.areaType = 2
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    importCustomers(){
      this.dialogImportVisible = true
    },
    exportCustomers(){
      this.exportStatus = true
      exportCustomers(this.listQuery).then(res => {
         if(res.code === 20000){
           this.exportData = res.data
           import('@/vendor/Export2Excel').then(excel => {
             const tHeader = ['类型', '用户编号', '水司编号', '省', '市','区','小区','楼栋','单元','楼层','门牌号','手机号','数据标识']
             const data = this.exportData
             excel.export_json_to_excel({
               header: tHeader,
               data,
               filename: '用户数据',
               autoWidth: true,
               bookType: 'xlsx'
             })
             this.exportStatus = false
           })
         }
      }).catch(err => {

      })
      this.listLoading = false
    },
    updateCustomer(row){
      this.resetTemp()
      this.dialogStatus = 'update'
      this.temp = Object.assign({},row)
      this.temp.area_path = this.temp.area_path.split(',')
      this.dialogFormVisible = true
      this.$nextTick(() => {//等待子组件mount再执行
        this.$refs['areaSelector'].setSelectedNodes(this.temp.area_path)
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const tempData = Object.assign({}, this.temp)
          tempData.area_path = ''
          updateCustomer(tempData).then(response => {
            if(response.code === 20000){
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
              this.getCustomerList()
            }else{
              this.$notify({
                title: 'Failed',
                message: '更新失败',
                type: 'error',
                duration: 3000
              })
            }
          })
          this.submitLoading = false
        }
      })
    },
    handleCreate(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const tempData = Object.assign({}, this.temp)
          tempData.area_path = tempData.area_path.join(',')
          addCustomer(tempData).then(response =>{
            if(response.code === 20000){
              this.$notify({
                title: 'Success',
                message: '添加成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
              this.getCustomerList()
            }else{
              this.$notify({
                title: 'Failed',
                message: '添加失败',
                type: 'error',
                duration: 3000
              })
            }
          })
          this.submitLoading = false
        }
      })
    },
    handleDelete(){
      let selectRows = this.$refs.customerTable.selection
      let ids = []
      selectRows.forEach(function (row) {
        ids.push(row.id)
      })
      if(ids.length === 0){
        this.$message.warning('请选择用户')
        return
      }
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomer({'ids':ids}).then(response => {
          if(response.code === 20000){
            this.$message.success("成功删除")
            this.getCustomerList()
          }else{
            this.$message.error(response.message)
          }
        })
      })
    },
    onSelectArea(data){
      if(data !== ''){
        this.temp.area_path = data.path
        this.temp.area_code = data.value
        this.temp.area_name = data.pathLabels.join('/')
      }else{
        this.temp.area_path = ''
        this.temp.area_code = ''
        this.temp.area_name = ''
      }
    },
    onSelectBuilding(data){
      if(data !== ''){
        this.importData = {code:data.value}
      }else{
        this.importData = ''
      }
    },
    formatType(value){
      return getCustomerTypeText(value)
    },
    resetTemp(){
      this.temp = {
        id:'',
        area_code:'',
        area_name:'',
        customer_name:'',
        customer_type:'',
        room_number:'',
        identity_card:'',
        identity_type:'',
        mobile:'',
        establish_time:'',
        name:'',
      }
    },
    resetQueryParams(){
      this.listQuery = {
        id:0,
        page:1,
        pageSize:20,
        name:''
      }
    }
  }
}
</script>
